package top.eggcode.setup.config.filter;

import org.slf4j.MDC;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 请求日志处理
 * Created at 2021/11/17 10:47
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public class LogInterceptor implements HandlerInterceptor {

    private final static String keyName = "requestId";

    @Override
    public boolean preHandle(@NonNull HttpServletRequest httpServletRequest,
                             @NonNull HttpServletResponse httpServletResponse, Object o) throws Exception {
        String id = UUID.randomUUID().toString().replace("-", "");
        MDC.put(keyName, id);
        httpServletResponse.setHeader("x-request-id", id);
        return true;
    }

    @Override
    public void postHandle(@NonNull HttpServletRequest httpServletRequest,
                           @NonNull HttpServletResponse httpServletResponse,
                           @NonNull Object o,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest httpServletRequest,
                                @NonNull HttpServletResponse httpServletResponse,
                                @NonNull Object o,
                                Exception e) throws Exception {
        MDC.remove(keyName);
    }
}
